import {Component, EventEmitter, OnInit, Output} from '@angular/core';
import {NzDescriptionsComponent, NzDescriptionsItemComponent} from "ng-zorro-antd/descriptions";
import {UserService} from "../../user/user.service";
import {User} from "../../@core/data/user";
import {ActivatedRoute} from "@angular/router";
import {NzCardComponent} from "ng-zorro-antd/card";
import {AsyncPipe, NgIf} from "@angular/common";
import {NzInputDirective} from "ng-zorro-antd/input";
import {FormsModule} from "@angular/forms";
import {NzButtonComponent} from "ng-zorro-antd/button";
import {NzTypographyComponent} from "ng-zorro-antd/typography";
import {BehaviorSubject, EMPTY} from "rxjs";
import {NzMessageService} from "ng-zorro-antd/message";

export interface UserDetailEvent {
  type: "init" | "update"
}

export interface UserDetailUpdateEvent extends UserDetailEvent {
  type: "update"
  user: User
}

@Component({
  selector: 'user-detail',
  standalone: true,
  imports: [
    NzDescriptionsComponent,
    NzDescriptionsItemComponent,
    NzCardComponent,
    NgIf,
    NzInputDirective,
    FormsModule,
    NzButtonComponent,
    NzTypographyComponent,
    AsyncPipe
  ],
  templateUrl: './user-detail.component.html',
  styleUrl: './user-detail.component.css'
})
export class UserDetailComponent implements OnInit {

  @Output() onUserInfoChange: EventEmitter<UserDetailEvent> = new EventEmitter<UserDetailEvent>()

  realNameSource = new BehaviorSubject<string>('')
  usernameSource = new BehaviorSubject<string>('')
  addressSource = new BehaviorSubject<string>('')
  ageSource = new BehaviorSubject<string>('')
  private userIdSource = new BehaviorSubject<string>('')

  constructor(private userService: UserService,
              private route: ActivatedRoute,
              private messageService: NzMessageService) {
  }

  ngOnInit(): void {
    this.route.params
      .subscribe({
          next: params => {
            const userId = params['userId']
            this.userIdSource.next(userId)
            this.userService.getUserById(userId)
              .subscribe({
                  next: res => {
                    if (res.username) {
                      this.usernameSource.next(res.username)
                    }
                    if (res.realName) {
                      this.realNameSource.next(res.realName)
                    }
                    if (res.age) {
                      this.ageSource.next(String(res.age))
                    }
                    if (res.address) {
                      this.addressSource.next(res.address)
                    }
                  },
                  error: error => {
                    this.messageService.error('获取用户详情失败：' + error.message)
                    return EMPTY
                  }
                }
              )
          },
          error: error => {
            console.error('获取路由id失败：' + error.message)
            return EMPTY
          }
        }
      )
  }

  realNameChange(realName: string): void {
    this.userService.editUser({
      id: this.userIdSource.value,
      realName: realName
    })
      .subscribe({
        next: () => {
          // 用户姓名修改的时候，通知 list 组件更新用户姓名列表
          let newUser: User = {id: this.userIdSource.value, realName}
          let userUpdateEvent: UserDetailUpdateEvent = {
            type: 'update',
            user: newUser
          }
          this.onUserInfoChange.emit(userUpdateEvent)
          this.realNameSource.next(realName)
          this.messageService.success('修改成功')
        },
        error: error => {
          this.messageService.error('修改失败：' + error.message)
        }
      })
  }

  ageChange(age: string): void {
    this.userService.editUser({
      id: this.userIdSource.value,
      age: Number(age)
    })
      .subscribe({
        next: () => {
          this.ageSource.next(age)
          this.messageService.success('修改成功')
        },
        error: error => {
          this.messageService.error('修改失败：' + error.message)
        }
      })
  }

  addressChange(address: string): void {
    this.userService.editUser({
      id: this.userIdSource.value,
      address: address
    }).subscribe({
      next: () => {
        this.addressSource.next(address)
        this.messageService.success('修改成功')
      },
      error: error => {
        this.messageService.error('修改失败：' + error.message)
      }
    })
  }
}
